package com.example.nio.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @auther:lgb
 * @Date: 2021/5/3
 */
public class BIOTcpClient {
    public static void main(String[] args)  {
        //定义缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        SocketChannel socketChannel = null;
        try {
            //打开SocketChannel
            socketChannel = SocketChannel.open();
            //设置为非阻塞模式
            socketChannel.configureBlocking(false);
            //连接服务
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 2333));
            while (true) {
                //这里的finishConnect是尝试连接，有可能返回false，因此使用死循环进行连接检查，确保连接已经正常建立。
                if (socketChannel.finishConnect()) {
                    System.out.println("客户端已连接到服务器");
                    int i = 0;
                    while (i < 5) {
                        //隔一耗秒钟写一条
                        TimeUnit.MILLISECONDS.sleep(1);
                        String info = "来自客户端的第" + (i++) + "条消息";
                        buffer.clear();
                        buffer.put(info.getBytes());
                        buffer.flip();
                        while (buffer.hasRemaining()) {
                            //给服务写消息
                            socketChannel.write(buffer);
                        }
                    }
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socketChannel != null) {
                    System.out.println("客户端Channel关闭");
                    socketChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
